package com.luokangtao.user.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.luokangtao.common.entity.RedisKeyCode;
import com.luokangtao.common.entity.Result;
import com.luokangtao.common.entity.StatusCode;
import com.luokangtao.common.handler.BaseException;
import com.luokangtao.common.util.JwtUtil;
import com.luokangtao.user.dto.LoginCondition;
import com.luokangtao.user.dto.LoginResult;
import com.luokangtao.user.entity.User;
import com.luokangtao.user.service.SysService;
import io.jsonwebtoken.Claims;
import io.lettuce.core.dynamic.codec.RedisCodecResolver;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户登陆/退出相关接口
 * @author luokangtao
 * @create 2019-07-23 12:17
 */
@Slf4j
@RestController
@RequestMapping("/sys")
@Api(value = "用户登陆/退出相关接口",tags = "用户登陆/退出相关接口")
public class SysController {

    //用户相关信息
    @Autowired
    private SysService sysService;

    //JWT工具类
    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 登录
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ApiOperation("用户登陆接口")
    public Result login(@RequestBody @Validated LoginCondition login) {
        //根据用户名和登陆密码查找用户信息
        User admin = sysService.findByLoginNameAndPassword(login.getLoginname(), login.getPassword());
        String adminString = JSONObject.toJSONString(admin);//用户信息对象转成json
        log.info("把用户信息转成字符串:[{}]",adminString);
        //如果用户信息不能null
        if(admin != null){
            //登录成功,生成token  暂时写死角色admin
            String token = jwtUtil.createJWT(admin.getLoginname(),adminString , "admin");
            // key = <用户登陆名,生成token>
            redisTemplate.boundHashOps(RedisKeyCode.LOGIN).put(login.getLoginname(),token);
            //组装数据 token  用户登陆名  用户头像
            LoginResult loginResult = new LoginResult().setToken(token).setLoginname(admin.getLoginname()).setUserpic(admin.getUserpic());
            //返回组装的结果集
            return new Result(true, StatusCode.OK, "登录成功",loginResult);
        }else{
            return new Result(true, StatusCode.LOGINERROR, "登录失败");
        }
    }

    /**
     * 退出登陆
     */
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    @ApiOperation("用户退出接口")
    public Result logout(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String authorization = request.getHeader("Authorization");
        log.info("退出接口头Authorization:[{}]",authorization);
        if(StrUtil.isNotBlank(authorization)){
            //解析token
            try {
                Claims claims = jwtUtil.parseJWT(authorization);
                log.info("jwt解析信息claims:"+claims);
                String id = claims.getId();
                redisTemplate.boundHashOps(RedisKeyCode.LOGIN).delete(id);
            }catch (Exception e){
                throw new BaseException(StatusCode.ERROR,"退出失败");
            }
            return Result.ok("退出成功");
        }else {
            return Result.error("退出失败");
        }
    }

}
